import '../../domain/entities/anime.dart';

/// 动漫数据模型
/// 对应Jikan API的JSON响应格式
class AnimeModel extends Anime {
  const AnimeModel({
    required super.id,
    required super.title,
    required super.titleJapanese,
    super.titleEnglish,
    super.titleSynonyms = const [],
    required super.imageUrl,
    required super.synopsis,
    required super.score,
    required super.status,
    required super.episodes,
    super.year,
    required super.season,
    required super.genres,
    required super.studios,
    super.trailer,
    super.url,
    super.ranked,
    super.popularity,
    super.members,
    super.favorites,
    super.aired,
    super.rating,
  });

  /// 从JSON创建AnimeModel
  factory AnimeModel.fromJson(Map<String, dynamic> json) {
    // 如果传入的json为null或空，返回默认对象
    if (json.isEmpty) {
      return AnimeModel(
        id: 0,
        title: '未知标题',
        titleJapanese: '',
        imageUrl: '',
        synopsis: '暂无简介',
        score: 0.0,
        status: '未知',
        episodes: 0,
        year: null,
        season: '未知',
        genres: const [],
        studios: const [],
      );
    }

    try {
      return AnimeModel(
        id: _parseInt(json['mal_id']),
        title: _parseString(json['title'], '未知标题'),
        titleJapanese: _parseString(json['title_japanese'], ''),
        titleEnglish: json['title_english']?.toString(),
        titleSynonyms: _parseTitleSynonyms(json['title_synonyms']),
        imageUrl: _parseImageUrl(json['images']),
        synopsis: _parseString(json['synopsis'], '暂无简介'),
        score: _parseScore(json['score']),
        status: _parseStatus(json['status']),
        episodes: _parseEpisodes(json['episodes']),
        year: _parseYear(json['year'] ?? json['aired']),
        season: _parseString(json['season'], '未知'),
        genres: _parseGenres(json['genres']),
        studios: _parseStudios(json['studios']),
        trailer: json['trailer']?['url']?.toString(),
        url: json['url']?.toString(),
        ranked: json['rank'] is int ? json['rank'] : null,
        popularity: json['popularity'] is int ? json['popularity'] : null,
        members: json['members'] is int ? json['members'] : null,
        favorites: json['favorites'] is int ? json['favorites'] : null,
        aired: _parseAired(json['aired']),
        rating: json['rating']?.toString(),
      );
    } catch (e) {
      // 如果任何解析失败，返回一个基本但安全的对象
      print('AnimeModel解析失败: $e');
      return AnimeModel(
        id: _parseInt(json['mal_id']),
        title: _parseString(json['title'], '未知标题'),
        titleJapanese: '',
        titleEnglish: null,
        titleSynonyms: const [],
        imageUrl: '',
        synopsis: '暂无简介',
        score: 0.0,
        status: '未知',
        episodes: 0,
        year: null,
        season: '未知',
        genres: const [],
        studios: const [],
        trailer: null,
        url: null,
        ranked: null,
        popularity: null,
        members: null,
        favorites: null,
        aired: null,
        rating: null,
      );
    }
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'mal_id': id,
      'title': title,
      'title_japanese': titleJapanese,
      'title_english': titleEnglish,
      'title_synonyms': titleSynonyms,
      'images': {
        'jpg': {
          'large_image_url': imageUrl,
        }
      },
      'synopsis': synopsis,
      'score': score,
      'status': status,
      'episodes': episodes,
      'year': year,
      'season': season,
      'genres': genres.map((genre) => {'name': genre}).toList(),
      'studios': studios.map((studio) => {'name': studio}).toList(),
      'trailer': {'url': trailer},
      'url': url,
      'rank': ranked,
      'popularity': popularity,
      'members': members,
      'favorites': favorites,
      'rating': rating,
    };
  }

  /// 转换为实体类
  Anime toEntity() {
    return Anime(
      id: id,
      title: title,
      titleJapanese: titleJapanese,
      titleEnglish: titleEnglish,
      titleSynonyms: titleSynonyms,
      imageUrl: imageUrl,
      synopsis: synopsis,
      score: score,
      status: status,
      episodes: episodes,
      year: year,
      season: season,
      genres: genres,
      studios: studios,
      trailer: trailer,
      url: url,
      ranked: ranked,
      popularity: popularity,
      members: members,
      favorites: favorites,
      aired: aired,
      rating: rating,
    );
  }

  /// 从实体类创建AnimeModel
  static AnimeModel fromEntity(Anime anime) {
    return AnimeModel(
      id: anime.id,
      title: anime.title,
      titleJapanese: anime.titleJapanese,
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms,
      imageUrl: anime.imageUrl,
      synopsis: anime.synopsis,
      score: anime.score,
      status: anime.status,
      episodes: anime.episodes,
      year: anime.year,
      season: anime.season,
      genres: anime.genres,
      studios: anime.studios,
      trailer: anime.trailer,
      url: anime.url,
      ranked: anime.ranked,
      popularity: anime.popularity,
      members: anime.members,
      favorites: anime.favorites,
      aired: anime.aired,
      rating: anime.rating,
    );
  }

  /// 解析状态
  static String _parseStatus(dynamic status) {
    if (status == null) return '未知';
    
    final statusStr = status.toString().toLowerCase();
    switch (statusStr) {
      case 'currently airing':
        return 'Currently Airing'; // 保持原状态，在UI层转换
      case 'finished airing':
        return 'Finished Airing';
      case 'not yet aired':
        return 'Not yet aired';
      default:
        return status.toString();
    }
  }

  /// 解析类型列表
  static List<String> _parseGenres(dynamic genres) {
    if (genres == null) return [];
    
    if (genres is List) {
      return genres
          .map((genre) => genre['name']?.toString() ?? '')
          .where((name) => name.isNotEmpty)
          .toList();
    }
    
    return [];
  }

  /// 解析制作公司列表
  static List<String> _parseStudios(dynamic studios) {
    if (studios == null) return [];
    
    if (studios is List) {
      return studios
          .map((studio) => studio['name']?.toString() ?? '')
          .where((name) => name.isNotEmpty)
          .toList();
    }
    
    return [];
  }

  /// 解析播出时间
  static String? _parseAired(dynamic aired) {
    if (aired == null) return null;
    
    try {
      if (aired is Map) {
        final from = aired['from'];
        final to = aired['to'];
        
        if (from != null) {
          if (to != null) {
            return '$from 至 $to';
          } else {
            return '从 $from 开始';
          }
        }
      }
    } catch (e) {
      // 解析失败时忽略
    }
    
    return null;
  }

  /// 解析标题别名
  static List<String> _parseTitleSynonyms(dynamic synonyms) {
    if (synonyms == null) return [];
    
    if (synonyms is List) {
      return synonyms
          .map((title) => title?.toString() ?? '')
          .where((title) => title.isNotEmpty)
          .toList();
    }
    
    return [];
  }

  /// 解析图片URL
  static String _parseImageUrl(dynamic images) {
    if (images == null) return '';
    
    try {
      if (images is Map) {
        final jpg = images['jpg'];
        if (jpg is Map) {
          return jpg['large_image_url'] ?? jpg['image_url'] ?? '';
        }
      }
    } catch (e) {
      // 解析失败时返回空字符串
    }
    
    return '';
  }

  /// 解析评分
  static double _parseScore(dynamic score) {
    if (score == null) return 0.0;
    
    try {
      if (score is num) {
        return score.toDouble();
      }
      if (score is String) {
        return double.tryParse(score) ?? 0.0;
      }
    } catch (e) {
      // 解析失败时返回0.0
    }
    
    return 0.0;
  }

  /// 解析集数
  static int _parseEpisodes(dynamic episodes) {
    if (episodes == null) return 0;
    
    try {
      if (episodes is int) {
        return episodes;
      }
      if (episodes is String) {
        return int.tryParse(episodes) ?? 0;
      }
    } catch (e) {
      // 解析失败时返回0
    }
    
    return 0;
  }

  /// 解析年份
  static int? _parseYear(dynamic year) {
    if (year == null) return null;
    
    try {
      if (year is int) {
        return year;
      }
      if (year is String) {
        return int.tryParse(year);
      }
      if (year is Map) {
        // 处理aired对象
        final prop = year['prop'];
        if (prop is Map) {
          final from = prop['from'];
          if (from is Map) {
            final yearValue = from['year'];
            if (yearValue is int) {
              return yearValue;
            }
          }
        }
      }
    } catch (e) {
      // 解析失败时返回null
    }
    
    return null;
  }

  /// 复制并修改
  AnimeModel copyWith({
    int? id,
    String? title,
    String? titleJapanese,
    String? titleEnglish,
    List<String>? titleSynonyms,
    String? imageUrl,
    String? synopsis,
    double? score,
    String? status,
    int? episodes,
    int? year,
    String? season,
    List<String>? genres,
    List<String>? studios,
    String? trailer,
    String? url,
    int? ranked,
    int? popularity,
    int? members,
    int? favorites,
    String? aired,
    String? rating,
  }) {
    return AnimeModel(
      id: id ?? this.id,
      title: title ?? this.title,
      titleJapanese: titleJapanese ?? this.titleJapanese,
      titleEnglish: titleEnglish ?? this.titleEnglish,
      titleSynonyms: titleSynonyms ?? this.titleSynonyms,
      imageUrl: imageUrl ?? this.imageUrl,
      synopsis: synopsis ?? this.synopsis,
      score: score ?? this.score,
      status: status ?? this.status,
      episodes: episodes ?? this.episodes,
      year: year ?? this.year,
      season: season ?? this.season,
      genres: genres ?? this.genres,
      studios: studios ?? this.studios,
      trailer: trailer ?? this.trailer,
      url: url ?? this.url,
      ranked: ranked ?? this.ranked,
      popularity: popularity ?? this.popularity,
      members: members ?? this.members,
      favorites: favorites ?? this.favorites,
      aired: aired ?? this.aired,
      rating: rating ?? this.rating,
    );
  }

  /// 安全解析整数
  static int _parseInt(dynamic value) {
    if (value == null) return 0;
    
    if (value is int) return value;
    if (value is String) return int.tryParse(value) ?? 0;
    if (value is double) return value.toInt();
    
    return 0;
  }

  /// 安全解析字符串
  static String _parseString(dynamic value, String defaultValue) {
    if (value == null) return defaultValue;
    return value.toString();
  }
} 